package com.norteksoft.projectname.module1.web;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.norteksoft.projectname.module1.model.Attachment;
import com.norteksoft.projectname.module1.model.Person;
import com.norteksoft.projectname.module1.service.PersonManager;
import com.norteksoft.struts.Constants;
import com.norteksoft.struts.dao.support.Page;
import com.norteksoft.struts.web.StrutsAction;
import com.norteksoft.struts.web.ec.ECInfomationBean;
import com.norteksoft.struts.web.ec.PaginationUtil;


/**
 * @spring.bean name="/actions/personDispatcher" singleton="false"
 * @author huhc
 *
 */
public class PersonDispatcher extends StrutsAction {
	private static Log log=LogFactory.getLog(PersonDispatcher.class);
	private PersonManager personManager;
	/**
	 * @spring.property ref="personManager"
	 * @param personManager
	 */
	public void setPersonManager(PersonManager personManager) {
		this.personManager = personManager;
	}
	

	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		return mapping.findForward(Constants.ADD);
	}
	
	public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		try{
			String departmentId=request.getParameter("departmentId") ;
			String personId=request.getParameter("id");
			Person person=null;
			Long attachmentId=null;
			if(StringUtils.isBlank(personId)){
				person=new Person();
			}else{
				person=(Person) personManager.get(Long.valueOf(personId));
				attachmentId=personManager.getAttachmentId(Long.valueOf(personId));
			}
			this.bindEntity(form,person);
			//通过这种方式可以获取不定个数的file
			//form.getMultipartRequestHandler().getFileElements();
			DynaBean dynaForm=(DynaBean)form;
			FormFile photo=(FormFile)dynaForm.get("photo");
			boolean newFile=false;
			if(photo.getFileName()!=null && !"".equals(photo.getFileName())){
				newFile=true;
				person.setPhotoName(photo.getFileName());
				Attachment attachment=new Attachment();
				attachment.setContent(photo.getFileData());
				attachment.setPerson(person);
				person.setAttachment(attachment);
			}
			
			//log.debug("$$$$$$$$$$$$$$$$$$:"+file.getFileName());
			personManager.save(person,departmentId);
			//跟新人员信息时如果上传了新附件则需要删除旧的附件
			if(newFile && StringUtils.isNotBlank(personId)){
				personManager.deleteAttachment(attachmentId);
			}
			StringBuffer url=new StringBuffer("/actions/personDispatcher.do?method=list&departmentId=");
			url.append(person.getBelongDep().getId());
			refreshOpener(url, request, response);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return null;
	}
	
	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Long id=Long.valueOf(request.getParameter("id"));
		Person person=(Person) personManager.get(id);
		this.bindForm(form, person);
		//request.setAttribute("person", person);
		return mapping.findForward(Constants.EDIT);
	}
	
	public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Long id=Long.valueOf(request.getParameter("id"));
		Person person=(Person) personManager.get(id);
		this.bindForm(form, person);
		personManager.save(person);
		return mapping.findForward(Constants.RETURN_TO_lIST);
	}
	
	public ActionForward show(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Long id=Long.valueOf(request.getParameter("id"));
		Person person=(Person) personManager.get(id);
		//this.bindForm(form, person);
		request.setAttribute("person", person);
		return mapping.findForward(Constants.SHOW);
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String[] ids=request.getParameterValues("docId");
		for(int i=0;i<ids.length;i++){
			Long id=Long.valueOf(ids[i]);
			personManager.removeById(id);
		}
		ActionForward f=mapping.findForward(Constants.RETURN_TO_lIST);
		f=new ActionForward(f.getPath()+"&departmentId="+request.getParameter("departmentId"));
		return f;
	}
	
	public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
//		int totalRows=personManager.getCount();		
//		Page page=new Page("from Person p where p.belongDep.id=?");
//		page.prepare(totalRows, request);
//		List personList=personManager.list(page.getQuery(), page.getStart(), Constants.PAGE_SIZE,new Object[]{departmentId});
		
		String departmentId=request.getParameter("departmentId");
		ECInfomationBean ecInfo = PaginationUtil.initializeEC(request);
		Page page=personManager.pagedQuery(getHql(ecInfo.getSortQuery()), ecInfo.getCurPage(), ecInfo.getPageSize(), new Object[]{departmentId});
		request.setAttribute("departmentId", departmentId);
		request.setAttribute("personList", page.getResult());
//		ec必须设置这个属性
		request.setAttribute("totalRows", new Integer(page.getTotalCount()));
		return mapping.findForward(Constants.LIST);
	}
	
	private String getHql(String sortQuery) {
		// TODO Auto-generated method stub
		StringBuffer sb=new StringBuffer("from Person p where p.belongDep.id=?");
		sb.append(sortQuery);
		return sb.toString();
	}
	
	public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		try{
		String personId=request.getParameter("personId");
		Person person=(Person)personManager.get(Long.valueOf(personId));
		Attachment	attachment=person.getAttachment();
		log.debug("***************attachemntId:"+attachment.getId());
		
		BufferedInputStream bis=new BufferedInputStream(new ByteArrayInputStream(attachment.getContent()));
		response.reset();
		response.setContentType("application/x-download");
		
		String fileName = new String(person.getPhotoName().getBytes(), "iso8859-1");
		log.debug("*******"+fileName);
		response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
		OutputStream out=response.getOutputStream();
		byte[] buffer = new byte[4096];
		int size = 0;
		while ((size = bis.read(buffer, 0, buffer.length)) != -1) {
			out.write(buffer, 0, size);
		}
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
}
